package com.esun.cheetah.view.personal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.esun.cheetah.R;
import com.esun.cheetah.biz.personal.attention.AddAttenTeam;
import com.esun.cheetah.biz.personal.attention.CancelAttenTeam;
import com.esun.cheetah.biz.personal.personalinfo.UserInfo;
import com.esun.cheetah.config.BizCode;
import com.esun.cheetah.config.Config;
import com.esun.cheetah.config.Key;
import com.esun.cheetah.config.Language;
import com.esun.cheetah.model.match.matchinfo.SearchTeamInfo;
import com.esun.cheetah.network.AbsInferiorityCommunicater;
import com.esun.cheetah.view.custom.CustomProgressDialog;
import com.esun.util.Tools;

public class AddTeamAct extends Activity {
	/** 取消Button */
	private Button btnCancel;
	/** 清除Button */
	private Button btClean;
	/** 搜索结果的listView */
	private ListView resultListView;
	/** 搜索球队结果的List */
	private List<SearchTeamInfo> listSearchTeamInfo;
	private static ImageButton imAddAtten;
	private ResultAdapter resultAdapter;
	private static SearchTeamInfo searInfo;
	private CustomProgressDialog progress ;
	/** 搜索handler */
	Handler searchHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case Config.COMMUNICATER_SUCCESS:
				break;
			case Config.SEARCH_TEAM_SUCESSFUL:
				resultAdapter = new ResultAdapter(AddTeamAct.this, listSearchTeamInfo);
				resultListView.setAdapter(resultAdapter);
				progressDiss();
				break;
			case Config.NO_RELATE_TEAM:
				Toast.makeText(AddTeamAct.this, "对不起，没有与之相关的球队", Toast.LENGTH_SHORT).show();
				progressDiss();
				break;
			case Config.HOT_TEAM_SUCESSFUL:
				resultAdapter = new ResultAdapter(AddTeamAct.this, listSearchTeamInfo);
				resultListView.setAdapter(resultAdapter);
				progressDiss();
				break;
			case Config.COMMUNICATER_EXCEPTION:
			case Config.COMMUNICATER_FAIL:
				 if(!Tools.networkStatus(AddTeamAct.this)){
		    		  Tools.TipNetworkError(AddTeamAct.this, Language.INTERNET_FAIL);
		    	  }
				progressDiss();
				break;
			default:
				break;
			}
		}
	};
	/** 添加球队handler */
	Handler addSearhTeamHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case Config.COMMUNICATER_SUCCESS:
				imAddAtten.setImageResource(R.drawable.icon_default_star_add_team_2);
				searInfo.setIsguanzhu("1");
				Toast.makeText(AddTeamAct.this, "添加球队成功", Toast.LENGTH_LONG).show();
				break;
			case Config.COMMUNICATER_EXCEPTION:
			case Config.COMMUNICATER_FAIL:
				  if(!Tools.networkStatus(AddTeamAct.this)){
		    		  Tools.TipNetworkError(AddTeamAct.this, Language.INTERNET_FAIL);
		    		  return;
		    	  }
				break;
			default:
				break;
			}
		}
	};
	/** 取消关注球队handler */
	Handler cancelHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case Config.COMMUNICATER_SUCCESS:
				imAddAtten.setImageResource(R.drawable.icon_default_staradd);
				Toast.makeText(AddTeamAct.this, "取消关注球队成功", Toast.LENGTH_LONG).show();
				searInfo.setIsguanzhu("0");
				break;
			case Config.COMMUNICATER_EXCEPTION:
			case Config.COMMUNICATER_FAIL:
				 if(!Tools.networkStatus(AddTeamAct.this)){
		    		  Tools.TipNetworkError(AddTeamAct.this, Language.INTERNET_FAIL);
		    	  }
				progressDiss();
				break;
			default:
				break;
			}
		}
	};
	/** 自动输入框 */
	private AutoCompleteTextView actSearchTeam;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_team);
		inintViews();

	}

	private void inintViews() {
		progress = new CustomProgressDialog(AddTeamAct.this) ;
	  	progress.setMessage("加载数据中...") ;
	  	progress.show() ;
		btnCancel = (Button) findViewById(R.id.btnCancel);
		btnCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		resultListView = (ListView) findViewById(R.id.lvSearchContent);
		resultListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				SearchTeamInfo searchTeamInfo = (SearchTeamInfo) (parent.getItemAtPosition(position));
				String teamName = searchTeamInfo.getTeamName();
				String league = searchTeamInfo.getLeague();
				String teamId = searchTeamInfo.getTeamId();
				Intent mIntent = new Intent(AddTeamAct.this, EventDetails.class);
				mIntent.putExtra(Config.TEAM_NAME, teamName);
				mIntent.putExtra(Config.TEAM_ID, teamId);
				mIntent.putExtra(Config.TEAM_LEAGUE, league);
				startActivity(mIntent);
			}
		});
		actSearchTeam = (AutoCompleteTextView) findViewById(R.id.actvSearchTeam);
		actSearchTeam.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				resultListView.setAdapter(new ResultAdapter(AddTeamAct.this, null));
				if (s.length() > 0) {
					btClean.setVisibility(View.VISIBLE);
					new SearchCom(searchHandler, s + "").startCommunicate();
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		btClean = (Button) findViewById(R.id.btClean);
		btClean.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				actSearchTeam.setText("");
				btClean.setVisibility(View.INVISIBLE);
			}
		});
	}

	/**
	 * 搜索球队接口 com.esun.cheetah.view.personal.SearchCom
	 * 
	 * @author 任付江 create at 2012-4-22 下午5:04:23
	 */
	public class SearchCom extends AbsInferiorityCommunicater {
		String key;

		public SearchCom(Handler handler) {
			super(handler);

		}

		public SearchCom(Handler handler, String key) {
			this(handler);
			SearchCom.this.key = key;
		}

		@Override
		public HashMap<String, String> comHashMap() {
			HashMap<String, String> searchMap = new HashMap<String, String>();
			searchMap.put(Key.KEY_ID, BizCode.SEARCH_TEAM_ID);
			searchMap.put(Key.ADD_TEAM_KEY, key);
			searchMap.put(Key.TYPE, Key.ZQ);
			searchMap.put(Key.KEY_USERNAME, UserInfo.getUserInfo().getUserName());
			return searchMap;
		}

		@Override
		public void getJsonContent(String serverRes) throws JSONException {
			JSONObject object = (JSONObject) new JSONTokener(serverRes).nextValue();
			JSONObject js = object.getJSONObject("data");
			JSONArray json = js.getJSONArray("list");
			listSearchTeamInfo = new ArrayList<SearchTeamInfo>();
			if (json.length() == 0) {
				searchHandler.sendEmptyMessage(Config.NO_RELATE_TEAM);
				return;
			}
			for (int i = 0; i < json.length(); i++) {
				SearchTeamInfo searchteamInfo = new SearchTeamInfo();
				JSONObject pearJs = json.getJSONObject(i);
				searchteamInfo.setIsguanzhu(pearJs.getString("isguanzhu"));
				searchteamInfo.setTeamId(pearJs.getString("id"));
				searchteamInfo.setTeamName(pearJs.getString("name"));
				searchteamInfo.setLeague(pearJs.getString("simplegbname"));
				listSearchTeamInfo.add(searchteamInfo);
			}
			searchHandler.sendEmptyMessage(Config.SEARCH_TEAM_SUCESSFUL);
		}
	}

	public class ResultAdapter extends BaseAdapter {
		private Context context;
		private List<SearchTeamInfo> listResultTeam;

		public ResultAdapter(Context context, List<SearchTeamInfo> listSearTeam) {
			this.context = context;
			this.listResultTeam = listSearTeam;

		}

		@Override
		public int getCount() {
			return listResultTeam != null ? listResultTeam.size() : 0;
		}

		@Override
		public Object getItem(int position) {
			if (listResultTeam != null && listResultTeam.size() > 0 && (position >= 0 && position < listResultTeam.size())) {
				return listResultTeam.get(position);
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			if (listResultTeam != null && listResultTeam.size() > 0 && (position >= 0 && position < listResultTeam.size())) {
				return Integer.valueOf(listResultTeam.get(position).getTeamId());
			}
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			LayoutInflater lif = LayoutInflater.from(context);
			convertView = lif.inflate(R.layout.search_team_result, null);
			TextView tvTeamName = (TextView) convertView.findViewById(R.id.tvTeamName);
			ImageButton imAddAtten1 = (ImageButton) convertView.findViewById(R.id.btAddAttenTeam);
			SearchTeamInfo searInfo2 = listResultTeam.get(position);
			final String name = listResultTeam.get(position).getTeamName();
			final String isguanzhu = listResultTeam.get(position).getIsguanzhu();
			if (isguanzhu.equals("1")) {
				imAddAtten1.setImageResource(R.drawable.icon_default_star_add_team_2);
			} else {
				imAddAtten1.setImageResource(R.drawable.icon_default_staradd);
			}
			imAddAtten1.setOnClickListener(new IsGuanZhu(searInfo2));
			tvTeamName.setText(name);
			return convertView;
		}
		
	}

	/**
	 * 热门球队 com.esun.cheetah.view.personal.SearchCom
	 * 
	 * @author 任付江 create at 2012-4-22 下午5:04:23
	 */
	public class HotCom extends AbsInferiorityCommunicater {

		public HotCom(Handler handler) {
			super(handler);

		}

		@Override
		public HashMap<String, String> comHashMap() {
			HashMap<String, String> searchMap = new HashMap<String, String>();
			searchMap.put(Key.KEY_ID, BizCode.HOT_TEAM_ID);
			searchMap.put(Key.KEY_LOTNAMEXX, Key.ZQ);
			searchMap.put(Key.KEY_USERNAME, UserInfo.getUserInfo().getUserName());
			return searchMap;
		}

		@Override
		public void getJsonContent(String serverRes) throws JSONException {
			JSONObject object = (JSONObject) new JSONTokener(serverRes).nextValue();
			JSONArray json = object.getJSONArray("data");
			listSearchTeamInfo = new ArrayList<SearchTeamInfo>();
			for (int i = 0; i < json.length(); i++) {
				SearchTeamInfo searchteamInfo = new SearchTeamInfo();
				JSONObject pearJs = json.getJSONObject(i);
				searchteamInfo.setIsguanzhu(pearJs.getString("isguanzhu"));
				searchteamInfo.setTeamId(pearJs.getString("id"));
				searchteamInfo.setTeamName(pearJs.getString("name"));
				searchteamInfo.setLeague(pearJs.getString("simplegbname"));
				listSearchTeamInfo.add(searchteamInfo);
			}
			searchHandler.sendEmptyMessage(Config.HOT_TEAM_SUCESSFUL);
		}
	}

	@Override
	protected void onResume() {
		new HotCom(searchHandler).startCommunicate();
		super.onResume();
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (!actSearchTeam.getText().toString().equals("")) {
			actSearchTeam.setText("");
		}
	}

	// 目的每次的对象不同,这样就是点击不同item的时候就是不通的实例
	public class IsGuanZhu implements View.OnClickListener {
		private SearchTeamInfo searInfo2;

		public IsGuanZhu(SearchTeamInfo searInfo3) {
			this.searInfo2 = searInfo3;
		}

		@Override
		public void onClick(View v) {
			searInfo = searInfo2;
			imAddAtten = (ImageButton) v;
			if (searInfo.getIsguanzhu().equals("1")) {
				new CancelAttenTeam(cancelHandler, searInfo.getTeamId()).startCommunicate();
			} else {
				new AddAttenTeam(addSearhTeamHandler, searInfo.getTeamName(), searInfo.getLeague(), searInfo.getTeamId() + "")
						.startCommunicate();
			}
		}
	}
	public void progressDiss(){
		if(progress.isShowing()){
			progress.dismiss();
		}
	}
}
